// Custom ESM created by Amit Mudgal Principal Consultant from MicroStrategy Professional Services on
// 9/22/2014 for American Express GMS(Global Merchant Services)

package com.AmericanExpress.Security;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.servlet.http.HttpServletRequest;

import com.microstrategy.web.app.AbstractExternalSecurity;
import com.microstrategy.web.app.ExternalSecurity;
import com.microstrategy.web.app.LoginForm;
import com.microstrategy.web.beans.RequestKeys;
import com.microstrategy.web.objects.WebIServerSession;
import com.microstrategy.web.objects.WebObjectsException;
import com.microstrategy.web.objects.WebObjectsFactory;
import com.microstrategy.web.platform.ContainerServices;
import com.microstrategy.web.platform.GenericCookie;
import com.AmericanExpress.Security.Encryption;
import com.AmericanExpress.Security.QueryExecution;

public class CustomLogonSecurity extends AbstractExternalSecurity  {
	
	private static String PROPERTIES_FILE_NAME;
	private static final String E0_Web = "localhost";
	private static final String E1_Web = "dcentral995.intra.aexp.com";
	private static final String E2_Web = "qcentral995.intra.aexp.com";
	private static final String E3_Web = "central995.intra.aexp.com";
	
	//LDAP variables
	private static String ssoURL; 
	private static String AdsServer;
	private static String AdsPwd;
	private static String AdsCN;
	private static String BaseSrchDN;
	//SQL DB variables
	private static String sqlHost;
	private static String sqlDB;
	private static String sqlDriver;
	private static String sqlUID;
	private static String sqlepwd;
	private static String sqlport;
	private static String sqlconurl;
	//SQL Query Variable
	private static String sql;
	private static String Updatesql;
	private static String UpdatesqlNDA;
	
	FetchCntSvcs fetchCntSvcs = null;
	public static int DaysDiffLogin=-1;
	public static String OrigURL="";
	public static String userName="";
	
	//MSTR IServer
	private static String mstrIServerNameN1;
	private static String mstrIServerNameN2;
	//private GenericCookie transferData;
	private GenericCookie gcUName;
	private Connection conn;
	/*
	 * 1. Called when a request comes in, and there is no valid session --> handlesAuthenticationRequest()
	 *    a. USE_MSTR_DEFAULT_LOGIN
	 *       processMSTRLoginForm() -- A session is created by MSTR Web --> canReconnectSession()
	 *    b. COLLECT_SESSION_NOW
	 *       getWebIServerSession() -- A sesssion is created by a custom ESM --> canReconnectSession()
	 *    c. USE_CUSTOM_LOGIN_PAGE
	 *       getCustomLoginURL()
	 * 
	 * conditions that invoke the handlesAuthenticationRequest() are:
	 *    a. NO_SESSION_FOUND = 1
	 *    b. SESSION_CLOSED = 2
	 *    c. INVALID_CREDENTIALS = 3
	 *    d. LOGIN_FIRST = 4
	 */
	public int handlesAuthenticationRequest(RequestKeys rk, ContainerServices cs, int reason) {
		System.out.println("** Enter into handlesAuthenticationRequest()");
		System.out.println("** Reason::"+reason);
		HttpServletRequest request = ((com.microstrategy.web.app.platform.ServletContainerServices)cs).getRequest();
		String hostname = request.getServerName();
		
		if(hostname.equalsIgnoreCase(E0_Web)){
			System.out.println("** Using E0_CredentialsVault");
			PROPERTIES_FILE_NAME = "E0_CredentialsVault";
		}
		if(hostname.equalsIgnoreCase(E1_Web)){
			System.out.println("** Using E1_CredentialsVault");
			PROPERTIES_FILE_NAME = "E1_CredentialsVault";
		}
		if(hostname.equalsIgnoreCase(E2_Web)){
			System.out.println("** Using E2_CredentialsVault");
			PROPERTIES_FILE_NAME = "E2_CredentialsVault";
		}
		if(hostname.equalsIgnoreCase(E3_Web)){
			System.out.println("** Using E3_CredentialsVault");
			PROPERTIES_FILE_NAME = "E3_CredentialsVault";
		}
		
		String requestURL = getURL(request);
		System.out.println("** RequestURL::"+requestURL);
		OrigURL=requestURL;
		ResourceBundle rb = ResourceBundle.getBundle(PROPERTIES_FILE_NAME);
		Enumeration <String> keys = rb.getKeys();
		ssoURL = rb.getString("CUSTOM_ERROR_URL");
		AdsServer = rb.getString("ADS_SERVER");
		AdsPwd = rb.getString("ADS_ADMIN_PWD");
		AdsCN = rb.getString("ADS_ADMIN_CN");
		BaseSrchDN = rb.getString("ADS_BASE_SRCH_DN");
		sqlHost = rb.getString("SQL_HOST");
		sqlDB = rb.getString("SQL_DB");
		sqlDriver = rb.getString("SQL_DRIVER");
		sqlUID = rb.getString("SQL_UID");
		sqlepwd = rb.getString("SQL_EPWD");
		sqlport = rb.getString("SQL_PORT");
		sqlconurl = rb.getString("SQL_CONNECTION_URL");
		sql = rb.getString("SQL_QUERY_STRING");
		Updatesql = rb.getString("UPDATE_SQL_QUERY_STRING");
		UpdatesqlNDA = rb.getString("UPDATE_SQL_QUERY_NDA_STRING");
		ssoURL = rb.getString("SSO_ROOT");
		mstrIServerNameN1 = rb.getString("MSTR_ISERVER_N1");
		mstrIServerNameN2 = rb.getString("MSTR_ISERVER_N2");

		fetchCntSvcs = new FetchCntSvcs(cs);
		Encryption ecrypt = new Encryption();
		String Uid = cs.getHeaderValue("sm_universalid");
		System.out.println("** Value read from HTTP Header for GUID " + Uid);
		GenericCookie LDAPCookie = getLDAPCookie(Uid, cs);
		Uid = getEmployeeId(LDAPCookie);
		System.out.println("** Uid::"+Uid);
		
		
		if(cs.getSessionAttribute("userIdEUP")==null || cs.getSessionAttribute("userIdEUP").equals("")){
			cs.setSessionAttribute("userIdEUP", Uid);
		}
		String user_type_code = "";
		try{
			ResultSet rsNZUTCode = fetchNZResultSet(Uid);
			if(rsNZUTCode!=null){
				if(rsNZUTCode.next()){
					user_type_code=rsNZUTCode.getString("USER_TYPE_CD");
					System.out.println("** USER_TYPE_CD in ESM::"+user_type_code);
					if(cs.getSessionAttribute("user_type_code")==null || cs.getSessionAttribute("user_type_code").equals("")){
						cs.setSessionAttribute("user_type_code", user_type_code);
					}
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		if(reason == NO_SESSION_FOUND || reason == SESSION_CLOSED) {
	    	System.out.println("** Logging in with user id 1: " + Uid  );
	    	return COLLECT_SESSION_NOW;
	    }
		
		
		ResultSet rsNZ = fetchNZResultSet(Uid);
		
		
		
		//couple testing cases
		//init: LDAPCookie!=null
		if(LDAPCookie!=null){
			if(isExistCostCenter(LDAPCookie)){
				System.out.println("** Is Existing in Cost Center;");
				if(isExistNZ(rsNZ)){
					System.out.println("** Is Existing in Netezza !");
					//setting the status code, if need this to work, we need to change "return USE_CUSTOM_LOGIN_PAGE"
					try {
						setStatusCode(rsNZ, Uid, cs, rk);
					} catch (NumberFormatException e) {
						e.printStackTrace();
					} catch (SQLException e) {
						e.printStackTrace();
					}
					//return to MSTR Home
					rk.remove("Uid");
					rk.remove("Pwd");
				    rk.add("Uid", Uid);
				    if(conn!=null){
				    	QueryExecution.SQLDisconnect(conn);	
				    }
				    System.out.println("** Logging in with user id0: " + Uid  );
					return USE_MSTR_DEFAULT_LOGIN;
				    //return USE_CUSTOM_LOGIN_PAGE;
				}else{
					System.out.println("** Is Not Existing in Netezza");
					//return to Pre-Approved Page - status code: 13
					cs.setSessionAttribute("userStatus", "13");
					if(conn!=null){
				    	QueryExecution.SQLDisconnect(conn);	
				    }
					return USE_CUSTOM_LOGIN_PAGE;
				}
			}else{
				if(isExistNZ(rsNZ)){
					//return to EPA submission confirmation status code: 14
					cs.setSessionAttribute("userStatus", "14");
					if(conn!=null){
				    	QueryExecution.SQLDisconnect(conn);	
				    }
					return USE_CUSTOM_LOGIN_PAGE;
				}else {
					//return to EPA 
					cs.setSessionAttribute("userStatus", "00");
					if(conn!=null){
				    	QueryExecution.SQLDisconnect(conn);	
				    }
					return USE_CUSTOM_LOGIN_PAGE;
				}
			}
		}else if(isExistNZ(rsNZ)){
			//return to EPA submission confirmation 
			//init: isExistNZ(rsNZ)
			if(conn!=null){
		    	QueryExecution.SQLDisconnect(conn);	
		    }
			cs.setSessionAttribute("userStatus", "14");
			return USE_CUSTOM_LOGIN_PAGE;
		}else{
			//return to EPA 
			if(conn!=null){
		    	QueryExecution.SQLDisconnect(conn);	
		    }
			cs.setSessionAttribute("userStatus", "00");
			return USE_CUSTOM_LOGIN_PAGE;
		}
		
		
	    
	    //return USE_CUSTOM_LOGIN_PAGE;
	}
	
	/*
	 * Called when COLLECT_SESSION_NOW is returned from handlesAuthenticationRequest() and not when using
	 * the default MSTR Wen Application's authentication.
	 * 
	 * If a valid SessionID is included in the RequestKeys, the existing session is used. Otherwise, a new session is created.
	 */
	  public WebIServerSession getWebIServerSession(RequestKeys reqKeys,ContainerServices cntSvcs){
		  //this module is for project login
		  Encryption ecrypt = new Encryption();
		  String Uid = cntSvcs.getHeaderValue("sm_universalid");
		  GenericCookie cookie = getLDAPCookie(Uid, cntSvcs);
		  System.out.println("** Authenticating to Project "+reqKeys.getValue("Project"));
		  
		  //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
		  Uid=getEmployeeId(cookie);
		  System.out.println("** Uid in WebIServerSession::"+Uid);
		  String strProject = reqKeys.getValue("Project");
		  String strServer = reqKeys.getValue("Server");
		  System.out.println("** StrServer::"+strServer);
		  if(strServer==null){
			  System.out.println("** New StrServer::"+mstrIServerNameN1);
			  strServer = mstrIServerNameN1;
		  }
		  WebIServerSession isess = null;
		  isess = WebObjectsFactory.getInstance().getIServerSession();
		  isess.setServerName(strServer);
		  isess.setProjectName(strProject);
		  isess.setServerPort(0);
		  isess.setLogin(Uid);
		  //System.out.println("** IServer Name is::"+isess.getServerName());
		 /* if(isess.getServerName()==null){
			  System.out.println("** I-Server Name is null;");
		  }*/
/*		  if(isess.isActive()){
			  System.out.println("** I-Server Session is avtive!");
		  }
*/		  try {
			  String sessionId = isess.getSessionID();
			  System.out.println("** SessionId::"+ sessionId);
			  String sessionServer=isess.getServerName();
			  System.out.println("** SessionServer Name::"+ sessionServer);
		  }catch (WebObjectsException e) {
			  isess.setServerName(mstrIServerNameN2);
			  try {
				  isess.refresh();
			  } catch (WebObjectsException e1) {
				  System.out.println("** Both nodes are down::"+mstrIServerNameN1+","+mstrIServerNameN2+" "+e1);
				  e1.printStackTrace();
			  }
			  //System.out.println("** WebObjectsException in IServerSession");
			  e.printStackTrace();
		  }
		  System.out.println("** Isess::"+isess);
		  return isess;
		  
	  }
	  
	  /*
	   * Called when an authentication or authorization failure results.
	   */
	  public String getFailureURL(int reqType, ContainerServices cntSvcs) {
		  System.out.println("** Enter into getFailureURL()");
		  return null; 
	  }
	  
	  /*
	   * Called only when handlesAuthenticationRequest() returns USE_CUSTOM_LOGIN_PAGE.
	   */
	  public String getCustomLoginURL(String originalURL, String desiredServer, int desiredPort, String desiredProject){
		  ContainerServices cntSvcs = fetchCntSvcs.getCntSvcs();
	      System.out.println("** Get Custom URL CalledQ!"+cntSvcs.getSessionAttribute("userStatus").toString());
	      if(cntSvcs.getSessionAttribute("userStatus") != null){	  
	    	  System.out.println("** Final before redirect " + cntSvcs.getSessionAttribute("userStatus").toString());
	    	  if("00".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
		        	//return "../plugins/CustomSecurity/jsp/Redirect_PreApprovedRegistration.jsp";
		    		  return "mstrWeb?pg=MsgEPA";
		    	  }
	    	  if("01".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	        	//return "../plugins/CustomSecurity/jsp/Redirect_PreApprovedRegistration.jsp";
	    		  return "plugins/CustomSecurity/jsp/Redirect_TermsandConditions.jsp";
	    	  }
	    	  if("02".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "/UserManager.do";
	    	  }
	    	  if("03".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/RequestReenablement.jsp";
	    	  }
	    	  if("04".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_TermsandConditions.jsp";
	    	  }
	    	  if("05".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_TermsandConditions.jsp";
	    	  }
	    	  if("06".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_PendingApprovals.jsp";
	    	  }
	    	  if("07".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_RejectedUser.jsp";
	    	  }
	    	  if("08".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_DeletedUser.jsp";
	    	  }
	    	  if("09".equals(cntSvcs.getSessionAttribute("userStatus").toString())){   
	    		  System.out.println("** Disabled user");
	    		  return "plugins/CustomSecurity/jsp/Redirect_DeletedUser.jsp";
	    	  }
	    	  if("10".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "/jsp/customizedPages/CustomError.jsp";
	    	  }
	    	  if("11".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_UserNDAPage.jsp";
	    	  }
	    	  if("12".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_XcptExpired.jsp";
	    	  }
	    	  if("13".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  //pre-approved page
	    		  //mstrWeb?pg=preApproved
	    		  //mstrWeb?pg=searchUser
	    		  return "/plugins/UAM/jsp/preApproved.jsp";
	    		  //return "mstrWeb?pg=preApproved";
	    	  }
	    	  if("14".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  //EPA submission confirmation
	    		  return "mstrWeb?pg=EPAcnf";
	    	  }
	    	  if("20".equals(cntSvcs.getSessionAttribute("userStatus").toString())){
	    		  return "plugins/CustomSecurity/jsp/Redirect_DisabledUser.jsp";
	    	  }
	      }

			/* MF Integration with MARC */
	      System.out.println("Checks to see if Merchant force application is run ?");
	      if("merchantForce".equals((String)cntSvcs.getSessionAttribute("partnerAppName"))){
	    	  System.out.println("** Inside partnerAppName Loop");
	    	  cntSvcs.setSessionAttribute("partnerAppName",null); //flush value
	    	  return "/jsp/customizedPages/MSTR_Desktop.jsp";
	      }/* MF Integration with MARC Ends */
	       
	      return "";
	  }
	  
	  // Cookie approach was used for consumption of information by UAM
	  public void CreateCookie(ContainerServices cs,String CookieName, String CookieData) {
		  GenericCookie cookie = cs.newCookie(CookieName, CookieData);
	      cookie.setPath("/");
	      cs.addCookieToResponse(cookie);
	  }
	  
	  private GenericCookie getLDAPCookie(String GUID, ContainerServices cs){
		  GenericCookie transferData = null;
		  String uid=null;
		  Encryption ecrypt = new Encryption();
		  Hashtable env = new Hashtable();
		  String adminName = AdsCN;
		  String adminPassword = ecrypt.Decrypt(AdsPwd);
		  String ldapURL = "ldap://" + AdsServer + ":401";
		  env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
		  env.put(Context.SECURITY_AUTHENTICATION,"simple");
		  env.put(Context.SECURITY_PRINCIPAL,adminName);
		  env.put(Context.SECURITY_CREDENTIALS,adminPassword);
		  env.put(Context.PROVIDER_URL,ldapURL);
		  try{
			  LdapContext ctx = new InitialLdapContext(env,null);
			  SearchControls searchCtls = new SearchControls();
			  String returnedAtts[]={"employeenumber", "givenName", "sn","axppmiddlename", "uid", "axppdepartmentid", "axppdepartment","axppbusiness_cd", "axppbusiness_descr", "axppcc-cd", "mail","axppmanagerid", "axppunit_cd", "axppunit_descr"}; 
			  searchCtls.setReturningAttributes(returnedAtts);
			  searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			  String searchFilter = "(axppguid=" + GUID + ")";
			  String searchBase = BaseSrchDN; 
			  int totalResults = 0; 
			  NamingEnumeration<SearchResult> answer = ctx.search(searchBase, searchFilter, searchCtls); 
			  String CookieData = "";
			  while (answer.hasMoreElements()){ 
				  SearchResult sr = (SearchResult)answer.next();
				  totalResults++;
				  System.out.println("** SearchResult::" + sr.getName());
				  Attributes attrs = sr.getAttributes(); 
				  if(attrs.get("employeeNumber") != null && attrs.get("employeeNumber").get(0) != null){
					  CookieData = attrs.get("employeeNumber").toString();
				  }else {
					  CookieData = "employeeNumber:null";
				  }
				  if(attrs.get("givenName") != null && attrs.get("givenName").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("givenName").toString();
					  userName = (String)attrs.get("givenName").get(0);
				  }else {
					  CookieData = CookieData + "|" + "givenName:null";
				  }
				  if(attrs.get("sn") != null && attrs.get("sn").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("sn").toString();
					  userName = userName + " " + (String) attrs.get("sn").get(0);
				  }else {
					  CookieData = CookieData + "|" + "sn:null";
				  }
				  if(attrs.get("axppmiddlename") != null && attrs.get("axppmiddlename").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("axppmiddlename").toString();
				  }else {
					  CookieData = CookieData + "|" + "axppmiddlename:null";
				  }
				  if(attrs.get("axppdepartment") != null && attrs.get("axppdepartment").get(0) != null){ 
					  CookieData = CookieData + "|" + attrs.get("axppdepartment").toString();
				  }else {
					  CookieData = CookieData + "|" + "axppdepartment:null";
				  }
				  if(attrs.get("axppdepartment_cd") != null && attrs.get("axppbusiness_cd").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("axppbusiness_cd").toString();
				  }else {
					  CookieData = CookieData + "|" + "axppbusiness_cd:null";
				  }
				  if(attrs.get("axppbusiness_descr") != null && attrs.get("axppbusiness_descr").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("axppbusiness_descr").toString();
				  }else {
					  CookieData = CookieData + "|" + "axppbusiness_descr:null";
				  }
				  if(attrs.get("axppcc-cd") != null && attrs.get("axppcc-cd").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("axppcc-cd").toString();
				  }else {
					  CookieData = CookieData + "|" + "axppcc-cd:null";
				  }
				  if(attrs.get("mail") != null && attrs.get("mail").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("mail").toString();
				  }else {
					  CookieData = CookieData + "|" + "mail:null";
				  }
				  if(attrs.get("axppmanagerid") != null && attrs.get("axppmanagerid").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("axppmanagerid").toString();
				  }else {
					  CookieData = CookieData + "|" + "axppmanagerid:null";
				  }
				  if(attrs.get("axppunit_cd") != null && attrs.get("axppunit_cd").get(0) != null){	
					  CookieData = CookieData + "|" + attrs.get("axppunit_cd").toString();
				  }else {
					  CookieData = CookieData + "|" + "axppunit_cd:null";
				  }
				  if(attrs.get("axppunit_descr") != null && attrs.get("axppunit_descr").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("axppunit_descr").toString();
				  }else{
					  CookieData = CookieData + "|" + "axppunit_descr:null";
				  } 
				  if(attrs.get("uid") != null && attrs.get("uid").get(0) != null){
					  CookieData = CookieData + "|" + attrs.get("uid").toString();
				  }else{
					  CookieData = CookieData + "|" + "uid:null";
				  } 
				  uid = (String)attrs.get("employeenumber").get();
			  }
			  	transferData = cs.newCookie("TransferData", CookieData);
				cs.addCookieToResponse(transferData);
			  	//CreateCookie(cs,"TransferData",CookieData);
			  	System.out.println("** Total results in LDAP found : " + totalResults); 
			  	ctx.close();
			}catch(Exception e){
				System.out.println("** ADS Search error: " + e); 
			    e.printStackTrace(); 
			}
		  return transferData;
	  }
	  
	  public String getEmployeeId(GenericCookie gc){
		  System.out.println("** GetEmployeeId");
		  String cookieStr="";
		  String uid = "";
		  if(gc!=null){
			  cookieStr = gc.getValue().trim();
			  System.out.println("** cookieStr::"+cookieStr);
			  String[] str = cookieStr.split("\\|");
			  for (int i = 0; i < str.length; i++) {
				  if(str[i].contains("employeeNumber")){
					  String temp[] = str[i].split("\\:");
					  uid = temp[1];
					  System.out.println("** LDAP Uid::"+uid);
				  }
			  }
		  }else{
			  System.out.println("GC is null !");
		  }
		  return uid.trim();
	  }
	  
	  private boolean isExistCostCenter(GenericCookie gc){
		  String cookieStr="";
		  String costCenter = "";
		  if(gc!=null){
			  cookieStr = gc.getValue().trim();
			  String[] str = cookieStr.split("\\|");
			  for (int i = 0; i < str.length; i++) {
				  if(str[i].contains("axppcc-cd")){
					  String temp[] = str[i].split("\\:");
					  costCenter = temp[1].trim();
					  if(costCenter==null || costCenter.equalsIgnoreCase("")){
						  return false;
					  }
					  System.out.println("** CostCenter::"+cookieStr);
				  }
			  }
		  }
		  return true;
	  }
	  
	  
	  private ResultSet fetchNZResultSet(String Uid){
		  Encryption ecrypt = new Encryption();
		  conn = QueryExecution.SQLconnect(sqlHost, sqlDB, sqlUID, ecrypt.Decrypt(sqlepwd), sqlDriver, sqlconurl, sqlport);
		  System.out.println("** Connection::"+conn);
		  ResultSet rs = QueryExecution.ExecSQLQuery(conn, sql.replaceAll("REPLACESTRING1", Uid));
		  System.out.println("** ResultSet::"+rs);
		  return rs;
	  }
	  
	  private boolean isExistNZ(ResultSet rs){
		  if(rs!=null){
			  try {
				if(rs.next()){
					System.out.println("** isExistNZ function(), and isExistNZ:: true");
					return true;
				}else{
					return false;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		  }else{
			  return false;
		  }
		  return true;
	  }
	  
	  private int setStatusCode(ResultSet rs, String Uid, ContainerServices cs, RequestKeys rk) throws NumberFormatException, SQLException{
		  try{
			  int UsertypeCD=-5;
			  int AdminCD=-5;
			  int daysdiffNDA=0;
			  int UserStaCD=-5;
			  String DayDiffNDA="";
			  while(rs.next()){
				  if(rs.getString("USER_TYPE_CD")==null){
					  UsertypeCD=0;
				  }else {
					  UsertypeCD = Integer.parseInt(rs.getString("USER_TYPE_CD").trim());
				  } 
				  if(rs.getString("USER_ADMIN_STA_CD")==null){
					  AdminCD=0;
				  }else {
					  AdminCD = Integer.parseInt(rs.getString("USER_ADMIN_STA_CD").trim());
				  }
				  if(rs.getString("DAYS_DIFF")==null){
					  daysdiffNDA=0;
				  }else {
					  daysdiffNDA = Integer.parseInt(rs.getString("DAYS_DIFF").trim());
				  }
				  if(rs.getString("DAYS_DIFF_LOGIN")==null){
					  DaysDiffLogin=0;
				  }else {
					  DaysDiffLogin = Integer.parseInt(rs.getString("DAYS_DIFF_LOGIN").trim());
				  }
				  if(rs.getString("DAYS_DIFF")==null){
					  DayDiffNDA=null;
				  }else {
					  DayDiffNDA = rs.getString("DAYS_DIFF");
				  }
				  if(rs.getString("USER_STA_CD")==null){
					  UserStaCD=0;
				  }else {
					  UserStaCD = Integer.parseInt(rs.getString("USER_STA_CD").trim());
				  }
			  }
			  System.out.println(UsertypeCD + " " + DaysDiffLogin + " " + daysdiffNDA );
		        
		        if(DayDiffNDA == null){
		        	
		        	cs.setSessionAttribute("userStatus", "05");
		        	//QueryExecution.SQLDisconnect(conn);
					return USE_CUSTOM_LOGIN_PAGE;
		        }
				if((UsertypeCD==1||UsertypeCD==2) && (AdminCD==3||AdminCD==5||AdminCD==8||AdminCD==9||AdminCD==10||
					AdminCD==11||AdminCD==12||AdminCD==13||AdminCD==16||AdminCD==17||AdminCD==20||
					AdminCD==21||AdminCD==22||AdminCD==23||AdminCD==25)  && DaysDiffLogin > 30  && UserStaCD==1 || daysdiffNDA > 30 ){
					cs.setSessionAttribute("userStatus", "05");
					System.out.println("Show Terms and Conditions Page");
					//QueryExecution.SQLDisconnect(conn);
					return USE_CUSTOM_LOGIN_PAGE;
				}
				
				if((AdminCD==1||AdminCD==2||AdminCD==18||AdminCD==19||AdminCD==24 )&& UserStaCD==1){
					cs.setSessionAttribute("userStatus", "06"	);
					System.out.println("Show Pending Approvals Page");
					//QueryExecution.SQLDisconnect(conn);
					return USE_CUSTOM_LOGIN_PAGE;
				}
				if((AdminCD==4||AdminCD==13)&& UserStaCD==1){
					cs.setSessionAttribute("userStatus", "07"	);
					System.out.println("Show Pending Rejected Users Page");
					//QueryExecution.SQLDisconnect(conn);
					return USE_CUSTOM_LOGIN_PAGE;
				}
				if((AdminCD==7)&& UserStaCD==2 && UsertypeCD==2){
					cs.setSessionAttribute("userStatus", "20"	);
					System.out.println("Show Disabled Users Page");
					//QueryExecution.SQLDisconnect(conn);
					return USE_CUSTOM_LOGIN_PAGE;
				}
				
				if((AdminCD==14)&& UserStaCD==1){
					cs.setSessionAttribute("userStatus", "08"	);
					//QueryExecution.SQLDisconnect(conn);
					System.out.println("Show Pending Deleted Users Page");
					return USE_CUSTOM_LOGIN_PAGE;
				}
				
				if((AdminCD==7)&& UserStaCD==2){
					cs.setSessionAttribute("userStatus", "09"	);
					//QueryExecution.SQLDisconnect(conn);
					System.out.println("Show Pending Disabled Users Page");
					return ExternalSecurity.USE_CUSTOM_LOGIN_PAGE;
				}
				if((AdminCD==15)&& UserStaCD==2){
					cs.setSessionAttribute("userStatus", "12");
					//QueryExecution.SQLDisconnect(conn);
					System.out.println("Show Exception Expired Page");
					return USE_CUSTOM_LOGIN_PAGE;
				}
				if(UserStaCD==2 && (!(AdminCD==7||AdminCD==15))){
					cs.setSessionAttribute("userStatus", "03");
					//QueryExecution.SQLDisconnect(conn);
					System.out.println("Show ?? Page");
					//return USE_CUSTOM_LOGIN_PAGE;
			        rk.remove("Uid");
			        rk.remove("Pwd");
			        rk.add("Uid", Uid);
			        
			        return USE_MSTR_DEFAULT_LOGIN;		
		
				}
				if((AdminCD==-5 && UsertypeCD==-5 && daysdiffNDA==0)){
					cs.setSessionAttribute("userStatus", "01"	);
					System.out.println("Show PreApproved registration Page");
					//QueryExecution.SQLDisconnect(conn);
					return USE_CUSTOM_LOGIN_PAGE;
					
				}
				
				if(UsertypeCD==2 && (AdminCD==3||AdminCD==5||AdminCD==8||AdminCD==9||AdminCD==10||
						AdminCD==11||AdminCD==12||AdminCD==13||AdminCD==16||AdminCD==17||AdminCD==20||
						AdminCD==21||AdminCD==22||AdminCD==23||AdminCD==25)  && DaysDiffLogin > 30  && UserStaCD==1 ){
					cs.setSessionAttribute("userStatus", "11"	);
					System.out.println("Show PreApproved registration Page");
					//QueryExecution.SQLDisconnect(conn);
					return USE_CUSTOM_LOGIN_PAGE;
				}
		  }catch(SQLException e){
			  e.printStackTrace();
		  }
		  rk.remove("Uid");
		  rk.remove("Pwd");
		  rk.add("Uid", Uid);
		  System.out.println("** Logging in with user id0: " + Uid  );
		  return USE_MSTR_DEFAULT_LOGIN;
	  }
	  private class FetchCntSvcs extends AbstractExternalSecurity{
		  private ContainerServices containerServices = null;
		  private Throwable e = null;
		  FetchCntSvcs(ContainerServices cntSvcs,Throwable thr){
			  containerServices = cntSvcs;
			  e = thr;
		  }
		  FetchCntSvcs(ContainerServices cntSvcs){
			  containerServices = cntSvcs;
		  }
		  public ContainerServices getCntSvcs(){
			  return containerServices;		
		  }
		  public Throwable getError(){
			  return e;		
		  }
	  }
		
	  public static String getURL(HttpServletRequest req) {
		  String scheme = req.getScheme();             // http
		  String serverName = req.getServerName();     // hostname.com
		  int serverPort = req.getServerPort();        // 80
		  String contextPath = req.getContextPath();   // /mywebapp
		  String servletPath = req.getServletPath();   // /servlet/MyServlet
		  String pathInfo = req.getPathInfo();         // /a/b;c=123
		  String queryString = req.getQueryString();          // d=789
			
		  // Reconstruct original requesting URL
		  StringBuffer url =  new StringBuffer();
		  url.append(scheme).append("://").append(serverName);
			
		  if ((serverPort != 80) && (serverPort != 443)) {
			    url.append(":").append(serverPort);
		  }
			
		  url.append(contextPath).append(servletPath);
			
		  if (pathInfo != null) {
			  url.append(pathInfo);
		  }
		  if (queryString != null) {
			  url.append("?").append(queryString);
		  }
		  //System.out.println("** enter into getURL() and return::"+url.toString());
		  return url.toString();
	  }

}
